package martian.m4gic.data
{
	import com.greensock.TweenMax;
	import com.greensock.easing.Linear;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	public class LFO extends EventDispatcher
	{
		private var t:TweenMax;
		
		private var f:Number = 0;
		private var e:Function = null;
		
		public var amplitude:Number = 1;
		public var offset:Number = 0;
		
		public var raw:Number = 1;
			public function get value():Number { return offset + raw * amplitude; }
		
		
		private var o:Object;
		private var p:String;
		
		public function LFO(frequency:int, ease:Function = null)
		{
			f = frequency / 4000;
			e = ease != null ? e : Linear.easeNone;
			t = new TweenMax(this, f, {	raw:-1,
										yoyo:true,
										repeat:-1,
										ease:e,
										paused:true,
										onUpdate:update
									  });
		}
		
		public function bind(object:Object, property:String):void
		{
			o = object;
			p = property;
		}
		
		public function start():void
		{
			if (t.paused) { t.resume(); }
		}
		
		public function pause():void
		{
			if (!t.paused) { t.pause(); }
		}
		
		public function stop():void
		{
			if (!t.paused)
			{
				t.pause();
				raw = 1;
			}
		}
		
		private function update():void
		{
			if (o != null) { if (o[p] != undefined) { o[p] = value; } }
			dispatchEvent(new Event(Event.CHANGE));
		}
	}
}